package cn.dubito.seller.service;

import cn.dubito.api.event.ProductStatusEvent;
import cn.dubito.entity.Product;
import cn.dubito.entity.enums.ProductStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liliang
 * @description: 产品相关服务
 * @date 2018/5/27.
 */
@Service
public class ProductRpcService implements ApplicationListener<ContextRefreshedEvent> {

    private static Logger LOG = LoggerFactory.getLogger(ProductRpcService.class);

    private static final String MQ_DESTINATION = "Consumer.cache.VirtualTopic.PRODUCT_STATUS";

    @Autowired
    private ProductCache productCache;


    /**
     * 查询全部
     *
     * @return
     */
    public List<Product> findAll() {
        return productCache.readAllCache();
    }

    /**
     * 查询单个
     *
     * @param id
     * @return
     */
    public Product findOne(String id) {
        Product product = productCache.readCache(id);
        if (product == null) {
            productCache.removeCache(id);
        }
        return product;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<Product> productList = findAll();
        productList.forEach(product -> {
            productCache.putCache(product);
        });
    }

    @JmsListener(destination = MQ_DESTINATION)
    public void updateCache(ProductStatusEvent event) {
        LOG.info("receive event: {}", event);
        productCache.removeCache(event.getId());
        if (ProductStatusEnum.IN_SELL.equals(event.getStatus())) {
            productCache.readCache(event.getId());
        }
    }
}
